package app

import (
	"path/filepath"
	"sync"
	"time"

	"github.com/go-apibox/utils"
	"github.com/tealeg/xlsx"
)

type GroupProduct struct {
	Version    int
	UpdateTime int64
	DoConfig   string
	Products   [][]*Product
}

var (
	groupProductMap    = make(map[uint32]*GroupProduct, 10)
	groupProductMapMux = new(sync.RWMutex)
)

func (app *App) initGroupProduct() error {
	now := time.Now().Unix() - int64(time.Now().Hour()*60*60+time.Now().Minute()*60+time.Now().Second())

	products := make([]*Product, 0, 100)
	if err := app.engine.Where("create_time>?", now).Find(&products); err != nil {
		return err
	}

	groupProductMapMux.Lock()
	defer groupProductMapMux.Unlock()

	for _, product := range products {
		gp, has := groupProductMap[product.DeviceGroupId]
		if !has {
			gp = &GroupProduct{
				Version:    0,
				UpdateTime: time.Now().Unix(),
				DoConfig:   "todo， 这里将会是刷页面配置",
				Products:   make([][]*Product, 0, 5),
			}
			gp.Products = append(gp.Products, make([]*Product, 0, 100))
			groupProductMap[product.DeviceGroupId] = gp
		}
		gp.Products[0] = append(gp.Products[0], product)
	}

	return nil

}

func importProduct(task *Task) error {
	xfile, err := xlsx.OpenFile(filepath.Join(app.config.DataDir, task.ProductPath))
	if err != nil {
		return err
	}
	for _, sheet := range xfile.Sheet {
		if len(sheet.Rows) < 2 {
			continue
		}
		products := make([]*Product, 0, len(sheet.Rows))
		for _, row := range sheet.Rows[2:] {
			if len(row.Cells[0].String()) == 0 {
				break
			}

			tmp := &Product{
				ProductId:       utils.RandUint32(),
				TaskId:          task.TaskId,
				DeviceGroupId:   task.DeviceGroupId,
				DeviceGroupName: task.DeviceGroupName,
				Account:         row.Cells[0].String(),
				ProductCode:     row.Cells[1].String(),
				ProductTitle:    row.Cells[2].String(),
				IsStart:         row.Cells[3].String(),
				ReleaseTime:     row.Cells[4].String(),
				CreateTime:      task.CreateTime,
			}

			products = append(products, tmp)
		}
		if _, err := app.engine.Insert(products); err != nil {
			app.logger.Error(err)
		}

		groupProductMapMux.Lock()
		gp, has := groupProductMap[task.DeviceGroupId]
		if !has {
			gp = &GroupProduct{
				Version:    0,
				UpdateTime: time.Now().Unix(),
				DoConfig:   "todo， 这里将会是刷页面配置",
				Products:   make([][]*Product, 0, 5),
			}
			gp.Products = append(gp.Products, make([]*Product, 0, 100))
			groupProductMap[task.DeviceGroupId] = gp
		} else {
			gp.Version++
		}
		gp.UpdateTime = time.Now().Unix()
		gp.Products = append(gp.Products, products)
		groupProductMapMux.Unlock()

	}
	return nil
}
